package org.scboy.rbac.service.imp;

import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import org.scboy.common.cache.SystemConfig;
import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacOrgDao;
import org.scboy.rbac.dao.RbacOrgRoleDao;
import org.scboy.rbac.dao.RbacOrgUserDao;
import org.scboy.rbac.dao.RbacUserAccountDao;
import org.scboy.rbac.dao.RbacUserInfoDao;
import org.scboy.rbac.dao.RbacUserRoleDao;
import org.scboy.rbac.dao.RbacUserTypeDao;
import org.scboy.rbac.service.UserService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.SM3;

@Service
public class UserServiceImp implements UserService {

	@Autowired
	EntityFactory factory;

	@Autowired
	SystemConfig config;
	
	@Override
	public Page page(Model model) {
		RbacOrgUserDao dao=factory.getDao(RbacOrgUserDao.class);
		return dao.queryPage(model);
	}

	@Override
	public Model get(String id) {
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);
		RbacUserRoleDao urdao=factory.getDao(RbacUserRoleDao.class);
		Model data= dao.get(Model.create().add("id", id));
		
		List<Model> roles= urdao.select(Model.create().add("userId", id));
		
		String [] roId=new String[roles.size()];
		for (int i=0;i<roles.size();i++) {
			roId[i]=roles.get(i).getString("orId");
		}
		data.add("orId", roId);
		return data;
	}

	@Override
	public Model get(String id, String password) {
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);
		return dao.get(Model.create().add("id", id).add("password",SM3.create().digestHex(password)));
	}

	@Override
	@Transactional
	public boolean add(Model model) {

		RbacUserRoleDao urdao=factory.getDao(RbacUserRoleDao.class);
		RbacOrgRoleDao ordao=factory.getDao(RbacOrgRoleDao.class);
		
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);
		
		RbacUserAccountDao accountDao=factory.getDao(RbacUserAccountDao.class);
		
		RbacOrgUserDao rouDao=factory.getDao(RbacOrgUserDao.class);
		
		long oldCount=dao.count(Model.create().add("idCard", model.get("idCard")));
		if(oldCount>0) {
			return false;
		}
		String userId=UUID.randomUUID().toString();
		
		//如果账号为空，使用身份证号码做为账号
		if(StrUtil.isEmpty(model.getString("loginAccount"))) {
			model.add("loginAccount", model.get("idCard"));
		}
		//如果有帐号字段，新增账号信息。
		if(StrUtil.isNotEmpty(model.getString("loginAccount"))){
			Model account=new Model();
			account.add("id", UUID.randomUUID().toString());
			account.add("loginAccount", model.getString("loginAccount").toUpperCase(Locale.ENGLISH));
			account.add("userId", userId);
			account.add("loginType", "local");
			account.add("loginState", 1);
			accountDao.insert(account);
		}
		//如果又组织ID存在，新增组织和用户的关系
		if(StrUtil.isNotEmpty(model.getString("orgId"))){
			Model userOrg=new Model();
			userOrg.add("id", UUID.randomUUID().toString());
			userOrg.add("orgId", model.getString("orgId"));
			userOrg.add("userId", userId);
			userOrg.add("addTime", new Date());
			userOrg.add("editTime", new Date());
			rouDao.insert(userOrg);
		}
		//如果存在密码，加密密码。
		if(StrUtil.isNotEmpty(model.getString("password"))){
			model.add("password",SM3.create().digestHex(model.getString("password")));
		}else{
			String  defaultPassword=config.getConfig("DEFAULT_PASSWORD");
			model.add("password",SM3.create().digestHex(defaultPassword));
		}
		//添加用户
		model.add("id",userId);
		if(model.get("userState")==null){
			model.add("userState",1);
		}
		
		String [] orId=model.getStringArray("orId");
		
		for (String _orId : orId) {
			Model orgRole=ordao.get(Model.create().add("id", _orId));
			Model userRole=Model.create();
			userRole.add("id", UUID.randomUUID().toString());
			userRole.add("orId", _orId);
			userRole.add("code", orgRole.getString("code"));
			userRole.add("orgId", orgRole.getString("orgId"));
			userRole.add("userId", userId);
			userRole.add("addTime", new Date());
			urdao.insert(userRole);
		}
		
		int resultCount=dao.insert(model);
		if(resultCount>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	@Transactional
	public boolean update(Model model) {
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);

		RbacUserRoleDao urdao=factory.getDao(RbacUserRoleDao.class);
		RbacOrgRoleDao ordao=factory.getDao(RbacOrgRoleDao.class);
		
		model.add("editTime", new Date());
		
		String [] orId=model.getStringArray("orId");
		
		//删除角色关联，并保存新的角色
		urdao.delete(Model.create().add("userId", model.getString("id")));
		for (String _orId : orId) {
			Model orgRole=ordao.get(Model.create().add("id", _orId));
			Model userRole=Model.create();
			userRole.add("id", UUID.randomUUID().toString());
			userRole.add("orId", _orId);
			userRole.add("code", orgRole.getString("code"));
			userRole.add("orgId", orgRole.getString("orgId"));
			userRole.add("userId", model.getString("id"));
			userRole.add("addTime", new Date());
			urdao.insert(userRole);
		}
		int result=dao.update(model,Model.create().add("id", model.getString("id")));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean rePassword(String id, String newPassword) {
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);
		int result=dao.update(
				Model.create().add("password",  SM3.create().digestHex(newPassword)),
				Model.create().add("id", id));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean checkState(String id) {
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);
		Model model=get(id);
		if(model==null){
			return false;
		}
		model.add("userState", !model.getBoolean("userState"));
		int resultCount=dao.update(model);
		if(resultCount>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	@Transactional
	public String importUser(List<Model> datas) {
		
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);

		RbacUserAccountDao accountDao=factory.getDao(RbacUserAccountDao.class);
		
		RbacOrgUserDao rouDao=factory.getDao(RbacOrgUserDao.class);
		
		RbacOrgDao orgDao=factory.getDao(RbacOrgDao.class);
		
		String msg="";
		int sum=0;
		for (Model model : datas) {
			if(StrUtil.isEmpty(model.getString("idCard"))) {
				continue;
			}
			if(!IdcardUtil.isValidCard(model.getString("idCard"))) {
				msg+="身份证："+model.getString("idCard")+"不正确。";
				sum++;
				continue;
			}
			Model userInfo=dao.get(Model.create().add("idCard", model.getString("idCard")));
			if(userInfo!=null) {
				accountDao.delete(Model.create().add("userId", userInfo.getString("id")));
				rouDao.delete(Model.create().add("userId", userInfo.getString("id")));
			}
			Model org=orgDao.get(Model.create().add("id", model.getString("orgId")));
			if(org!=null) {
				String userId=UUID.randomUUID().toString();
				if(userInfo!=null) {
					userId=userInfo.getString("id");
				}
				model.add("userCode", "0000");
				//如果有帐号字段，新增账号信息。
				if(StrUtil.isNotEmpty(model.getString("loginAccount"))){
					Model account=new Model();
					account.add("id", UUID.randomUUID().toString());
					account.add("loginAccount", model.getString("loginAccount").toUpperCase(Locale.ENGLISH));
					account.add("userId", userId);
					account.add("loginType", "local");
					account.add("loginState", 1);
					accountDao.insert(account);
				}
				//如果又组织ID存在，新增组织和用户的关系
				if(StrUtil.isNotEmpty(model.getString("orgId"))){
					Model userOrg=new Model();
					userOrg.add("id", UUID.randomUUID().toString());
					userOrg.add("orgId", model.getString("orgId"));
					userOrg.add("userId", userId);
					userOrg.add("addTime", new Date());
					userOrg.add("editTime", new Date());
					rouDao.insert(userOrg);
				}
				if(userInfo==null) {

					String  defaultPassword=config.getConfig("DEFAULT_PASSWORD");
					//如果存在密码，加密密码。
					model.add("password",SM3.create().digestHex(defaultPassword));
					//添加用户
					model.add("id",userId);
					model.add("userState",1);
					dao.insert(model);
				}else {
					dao.update(
							userInfo.add("userState", 1),
							userInfo.add("id", userInfo.getString("id"))
					);
				}
			}
			
		}
		if(sum!=0) {
			msg="有"+sum+"条导入失败。"+msg;
		}
		return msg;
	}

	@Override
	public List<Model> list(Model model) {
		RbacUserInfoDao dao=factory.getDao(RbacUserInfoDao.class);
		return dao.select(model);
	}

	@Override
	public Model getUserInfo(String id) {
		RbacUserInfoDao userInfoDao=factory.getDao(RbacUserInfoDao.class);
		RbacUserTypeDao userTypeDao=factory.getDao(RbacUserTypeDao.class);
		RbacUserRoleDao userRoleDao=factory.getDao(RbacUserRoleDao.class);
		
		//获取用户
		Model user = userInfoDao.get(Model.create().add("id", id).addNrc("password"));
		
		//获取用户类型
		Model userType=userTypeDao.get(Model.create().add("id", user.getString("userType")));
		user.add("userType", userType);
		
		//获取用户角色
		List<Model> roles= userRoleDao.queryList(Model.create().add("userId", user.getString("id")));
		user.add("roles", roles);
		
		return user;
	}

}
